<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="x-ua-compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>SSE 实时消息推送示例</title>
</head>

<body>
<div class="dialog-box" id="chat-gpt-dialog">
    <div class="header">
        <h2>与Ollama聊天</h2>
    </div>
    <div id="message-div"></div>
    <div class="content">
        <label for="user-input"></label>
        <textarea placeholder="输入消息..." id="user-input" rows="5" cols="100" style="margin-left: -9px;"></textarea>
        <button id="send-btn" onclick="send()">发送</button>
    </div>
    <div class="response">
        <div id="gpt-response" class="response-container"></div>
    </div>
    <div class="footer">
        <p id="gpt-footer" class="text-muted">由Ollama提供支持</p>
    </div>
</div>
</body>

<script>

    function send() {
        let user_input = document.getElementById('user-input')

        let messageClose = document.getElementById('message-div');
        messageClose.innerHTML = "";

        // 创建 EventSource 对象连接后端
        let source = new EventSource('/wxp-ollama/sse/stream?msg=' + user_input.value);
        source.onopen = () => {
            console.log('SSE连接打开');
        }

        // 处理接收到的消息
        source.onmessage = function (event) {
            console.log("event==>",event.data);
            // document.getElementById('message-div').text(event.data)
            // var div = document.createElement('p');
            // div.innerText = event.data;
            let message_div = document.getElementById('message-div');
            message_div.innerHTML = message_div.innerText + " " + event.data;
        };
        // 处理连接错误
        source.onerror = (error) => {
            console.error('SSE连接错误:', error);
        };
    }

</script>

<style>
    html, body {
        width: 100%;
        height: 100%;
    }

    .dialog-box {
        width: 100%;
        height: 80%;
        background-color: #f5f5f5;
        border: 1px solid #ccc;
        padding: 10px;
        box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.2);
        position: relative;
    }

    #message-div {
        width: 100%;
        height: 50%;
        float: right;
        background-color: antiquewhite;
    }

    .header {
        background-color: #333;
        color: #fff;
        padding: 5px;
        text-align: center;
    }

    .content {
        padding: 10px;
    }

    .response {
        padding: 10px;
    }

    .response-container {
        max-height: 200px;
        overflow-y: auto;
    }

    .footer {
        background-color: #333;
        color: #fff;
        padding: 5px;
        text-align: center;
    }
</style>

</html>